/*
 * Copyright (C) 2018 Zhejiang xiaominfo Technology CO.,LTD.
 * All rights reserved.
 * Official Web Site: http://www.xiaominfo.com.
 * Developer Web Site: http://open.xiaominfo.com.
 */

package com.hbxs.folder.conf;

import org.springframework.boot.ApplicationArguments;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;

/**
 * @ClassName: AppArgsSmartLifecycle
 * @Description: USEFULNESS(感知spring容器变化)
 * @author Radon
 * @date 2020/05/13
 *
 */
@Component
public class AppArgsSmartLifecycle implements SmartLifecycle{

    private boolean isRunning=false;

    private final ApplicationArguments applicationArguments;

    public AppArgsSmartLifecycle(ApplicationArguments applicationArguments) {
        this.applicationArguments = applicationArguments;
    }

    /**
     * start方法被执行前先看此方法返回值，返回false就不执行start方法了
     * @return
     */
    @Override
    public boolean isAutoStartup() {
        return true;
    }

    /**
     * 容器关闭后：
     * spring容器发现当前对象实现了SmartLifecycle，就调用stop(Runnable)，
     * 如果只是实现了Lifecycle，就调用stop()
     * @param runnable
     */
    @Override
    public void stop(Runnable runnable) {
        runnable.run();
    }

    /**
     * bean初始化完毕后，该方法会被执行
     */
    @Override
    public void start() {
        System.out.println("--------------------AppArgsSmartLifecycle--Start()------------------------------");

        System.out.println(applicationArguments);
        if (applicationArguments!=null){
            System.out.println(applicationArguments.getNonOptionArgs());
        }

        isRunning=true;
    }

    /**
     * 容器关闭后：
     * spring容器发现当前对象实现了SmartLifecycle，就调用stop(Runnable)，
     * 如果只是实现了Lifecycle，就调用stop()
     */
    @Override
    public void stop() {
        isRunning=false;

    }

    /**
     * 当前状态
     * @return
     */
    @Override
    public boolean isRunning() {
        return isRunning;
    }

    /**
     * 返回值决定start方法在众多Lifecycle实现类中的执行顺序(stop也是)
     * @return
     */
    @Override
    public int getPhase() {
        return Integer.MAX_VALUE;
    }
}
